<template>
  <div class="mobile-layout">
    <!-- 主内容区域 -->
    <div class="main-content">
      <router-view />
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-nav">
      <div class="nav-items">
        <template v-for="item in navItems" :key="item.name">
          <!-- 添加按钮使用 popover -->
          <n-popover
            v-if="item.name === 'add'"
            v-model:show="showEventTypePopover"
            trigger="click"
            placement="top"
            :show-arrow="true"
          >
            <template #trigger>
              <div class="nav-item nav-item-add">
                <n-icon :size="24" class="nav-icon">
                  <component :is="getIcon(item.icon)" />
                </n-icon>
                <span class="nav-label">{{ item.label }}</span>
              </div>
            </template>
            <EventTypePopover
              :event-types="eventsStore.eventTypes"
              @select="handleEventTypeSelect"
            />
          </n-popover>

          <!-- 其他按钮正常显示 -->
          <div
            v-else
            class="nav-item"
            :class="{ active: isActive(item.path) }"
            @click="handleNavClick(item)"
          >
            <n-icon :size="24" class="nav-icon">
              <component :is="getIcon(item.icon)" />
            </n-icon>
            <span class="nav-label">{{ item.label }}</span>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  Home as HomeIcon,
  Calendar as CalendarIcon,
  Add as AddIcon,
  Settings as SettingsIcon,
  BookOutline as BookIcon,
  StatsChart as StatsChartIcon
} from '@vicons/ionicons5'
import type { NavItem, EventType } from '@/types'
import { useEventsStore } from '@/stores/events'
import EventTypePopover from '@/components/EventTypePopover.vue'

const router = useRouter()
const route = useRoute()
const eventsStore = useEventsStore()

// Popover 显示状态
const showEventTypePopover = ref(false)

// 导航项配置
const navItems: NavItem[] = [
  { name: 'home', icon: 'home', path: '/home', label: '首页' },
  { name: 'nutrition', icon: 'stats-chart', path: '/nutrition-dashboard', label: '营养' },
  { name: 'add', icon: 'add', path: '', label: '添加' }, // add 按钮不需要 path，因为它是 popover 触发器
  { name: 'reserved2', icon: 'calendar', path: '/reserved2', label: '预留' },
  { name: 'settings', icon: 'settings', path: '/settings', label: '设置' }
]

// 获取图标组件
const getIcon = (iconName: string) => {
  const iconMap: Record<string, any> = {
    home: HomeIcon,
    calendar: CalendarIcon,
    add: AddIcon,
    settings: SettingsIcon,
    book: BookIcon,
    'stats-chart': StatsChartIcon
  }
  return iconMap[iconName] || HomeIcon
}

// 检查是否为当前路由
const isActive = (path: string) => {
  if (path === '/home') {
    return route.path === '/' || route.path === '/home'
  }
  return route.path.startsWith(path)
}

// 处理事件类型选择
const handleEventTypeSelect = (eventType: EventType) => {
  // 关闭 popover
  showEventTypePopover.value = false

  // 如果当前已经在创建页面，使用 replace 避免历史记录堆积
  if (route.path === '/events/create') {
    router.replace({
      path: '/events/create',
      query: { eventTypeId: eventType.id.toString() }
    })
  } else {
    // 如果不在创建页面，使用 push
    router.push({
      path: '/events/create',
      query: { eventTypeId: eventType.id.toString() }
    })
  }
}

// 处理导航点击
const handleNavClick = (item: NavItem) => {
  // 添加按钮由 popover 处理，不需要在这里处理
  if (item.name === 'add') {
    return
  }

  if (item.path.startsWith('/reserved')) {
    // 预留功能暂时不跳转
    window.$message?.info('功能开发中...')
  } else {
    router.push(item.path)
  }
}

// 初始化事件类型数据
onMounted(async () => {
  await eventsStore.init()
})
</script>

<style scoped>
.mobile-layout {
  /* 使用稳定的视口高度，避免地址栏隐藏导致的高度变化 */
  height: 100vh;
  /* 现代浏览器：使用动态视口高度 */
  height: 100dvh;
  /* 回退：使用稳定的视口高度变量 */
  height: calc(var(--stable-vh, 1vh) * 100);
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  position: relative;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: calc(60px + env(safe-area-inset-bottom)); /* 为底部导航栏留出空间 */
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: calc(60px + env(safe-area-inset-bottom));
  background: white;
  border-top: 1px solid #e0e0e0;
  padding: 8px 0;
  padding-bottom: calc(8px + env(safe-area-inset-bottom));
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.nav-items {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 4px 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 8px;
  min-width: 60px;
}

.nav-item:hover {
  background-color: #f0f0f0;
}

.nav-item.active {
  color: #667eea;
}

.nav-item.active .nav-icon {
  color: #667eea;
}

.nav-icon {
  margin-bottom: 2px;
  color: #666;
  transition: color 0.2s ease;
}

.nav-label {
  font-size: 12px;
  color: #666;
  transition: color 0.2s ease;
}

.nav-item.active .nav-label {
  color: #667eea;
  font-weight: 500;
}

/* 添加按钮特殊样式 */
.nav-item-add {
  position: relative;
}

.nav-item-add .nav-icon {
  background: #a466ea;
  color: white !important;
  border-radius: 50%;
  /* padding: 12px; */
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

/* 确保图标在圆圈内居中 */
.nav-item-add .nav-icon .n-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-item-add .nav-label {
  /* color: #667eea; */
  font-weight: 500;
}
</style>
